<template>
  <div>
    <el-form
      v-loading="loading"
      class="revise-item"
      ref="queryForm"
      :inline="true"
      :model="alterForm"
      label-width="80px"
    >
      <el-form-item
        :label="data.name"
        :prop="data.code"
        v-for="(data, index) in tableTitleData"
        :key="index"
      >
        <el-input
          v-model="alterForm[data.code]"
          :placeholder="data.promptContent"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          plain
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" plain
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="el-row">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="newPage"
        >
          新建
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="multiple"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" plain icon="el-icon-refresh">
          批量刷新
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" size="mini" plain icon="el-icon-turn-off">
          加锁
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="mini" plain icon="el-icon-open">
          解锁
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" plain icon="el-icon-download">
          导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="mini" plain icon="el-icon-upload2">
          导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" plain icon="el-icon-printer">
          打印
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" size="mini" plain icon="el-icon-notebook-2">
          查看日志
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" plain icon="el-icon-full-screen">
          扫一扫
        </el-button>
      </el-col>
    </el-row>

    <div class="table">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        align="center"
        style="width: 100%"
        ref="mulipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="selectionShow"
          type="selection"
          align="center"
          width="55"
        ></el-table-column>
        <el-table-column
          align="center"
          v-for="(tableTitleData, index) in tableTitleData"
          :key="index"
          :label="tableTitleData.name"
          :prop="tableTitleData.code"
          width="180"
        ></el-table-column>
        <el-table-column
          label="当前任务名称"
          prop="taskName"
          align="center"
          width="180"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope" v-if="reviseShow">
            <div v-if="scope.row.instance_id == ''">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="submitApplication(scope.row)"
                >提交申请</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['lemonPiggy-UDform:page:edit']"
                >修改</el-button
              >
            </div>
            <div v-else>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-document"
                @click="_handleView(scope.row)"
                >表单数据
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-time"
                @click="handleViewHistoryList(scope.row)"
                >审批历史
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                @click="handleViewProcessImg(scope.row)"
                >进度查看
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getValue"
      />
    </div>

    <el-Dialog :title="title" :visible.sync="open" width="500px" center>
      <el-row class="center-board-row" :gutter="formConf.gutter">
        <el-form
          :size="formConf.size"
          :label-position="formConf.labelPosition"
          :disabled="formConf.disabled"
          :label-width="formConf.labelWidth + 'px'"
        >
          <template-item
            v-for="(element, index) in drawingList"
            :key="element.renderKey"
            :drawing-list="drawingList"
            :element="element"
            :index="index"
            :active-id="activeId"
            :form-conf="formConf"
            @activeItem="activeFormItem"
          />
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel"> 取 消 </el-button>
        <el-button type="primary" @click="submitForm"> 确 定 </el-button>
      </span>
    </el-Dialog>
    <!-- 表单数据 -->
    <el-Dialog :title="title" :visible.sync="openForm" width="500px">
      <el-row class="center-board-row" :gutter="formConf.gutter">
        <el-form
          :size="formConf.size"
          :label-position="formConf.labelPosition"
          :label-width="formConf.labelWidth + 'px'"
          disabled
        >
          <template-item
            v-for="(element, index) in drawingList"
            :key="element.renderKey"
            :drawing-list="drawingList"
            :element="element"
            :index="index"
            :active-id="activeId"
            :form-conf="formConf"
            :clearAttributes="clearAttributes"
            @activeItem="activeFormItem"
          />
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel"> 关 闭 </el-button>
      </span>
    </el-Dialog>

    <!--审批历史对话框-->
    <el-dialog
      title="审批历史"
      :visible.sync="showHistoryTable"
      width="1000px"
      append-to-body
    >
      <!--审批历史表格-->
      <template>
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="70px"
        >
          <el-form-item label="任务名称" prop="activityName">
            <el-input
              v-model="queryParams.activityName"
              placeholder="请输入任务名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="办理人ID" prop="assignee">
            <el-input
              v-model="queryParams.assignee"
              placeholder="请输入办理人ID"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="cyan"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getHistoryList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loadingHistoryTable" :data="historyList">
          <el-table-column
            v-if="false"
            label="活动ID"
            align="center"
            prop="activityId"
            width="60"
          />
          <el-table-column
            label="活动名称"
            align="center"
            prop="activityName"
            width="140"
          />
          <el-table-column
            label="办理人ID"
            align="center"
            prop="assignee"
            width="90"
          />
          <el-table-column
            label="办理人"
            align="center"
            prop="assigneeName"
            width="80"
          />
          <el-table-column label="审批意见" align="center" prop="comment" />
          <el-table-column
            label="开始时间"
            align="center"
            prop="startTime"
            width="160"
          />
          <el-table-column
            label="结束时间"
            align="center"
            prop="endTime"
            width="160"
          />
          <el-table-column
            label="耗时"
            align="center"
            prop="durationInMillis"
            width="150"
          />
        </el-table>

        <!--v-show="total>0"-->
        <pagination
          v-show="false"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getHistoryList"
        />
      </template>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button @click="showHistoryTable = false">关闭</el-button>
      </div>
    </el-dialog>

    <!--进度查看对话框-->
    <el-dialog
      title="进度查看"
      :visible.sync="scheduleOpen"
      width="1000px"
      append-to-body
    >
      <div style="width: 100%; text-align: center;">
        <el-image :src="src" :preview-src-list="srcList"> </el-image>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button @click="scheduleOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPage } from "@/views/UDform/js/page";
import { format, formatTotalDateSub } from "@/utils/activiti/myUtil.js";
import request from "@/utils/request";
import {
  addPageValue,
  editPageValue,
  getPageValue,
  getAllPageValue,
  delPageValue,
  submitApply,
  getFromValue
} from "@/views/UDform/js/pageValue";
import { formConf } from "@/utils/generator/config";
import drawingDefalut from "@/utils/generator/drawingDefalut";
import TemplateItem from "./TemplateItem";
import ApplyAfter from "@/views/todoItem/Activiti/ApplyAfter/index";

export default {
  name: "TemplateList",
  components: {
    TemplateItem,
    ApplyAfter
  },
  data() {
    return {
      clearAttributes:0,
      dictData: [],
      showHistoryTable: false,
      scheduleOpen: false,
      srcList: [],
      src: "",
      // 显示搜索条件
      showSearch: true,
      historyList: [],
      drawingList: [],
      activeId: drawingDefalut[0].formId,
      activeData: drawingDefalut[0],
      formConf,
      id: "",
      tableData: [],
      tableTitleData: [],
      ids: [],
      open: false,
      openForm: false,
      title: "",
      selectionShow: true,
      reviseShow: true,
      addArg: [],
      addForm: {},
      alterForm: {},
      total: 0,
      loading: true,
      loadingHistoryTable: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processInstanceId: null,
        activityName: null,
        assignee: null
      },
      defaultValue: null
    };
  },
  created() {
    var url = window.location.href;
    var urls = url.split("Template/");
    this.id = urls[1];
    console.log(this.id);
    this.getPageData(this.id);
    this.getValue();
  },
  activated() {
    this.tableTitleData = [];
    this.getPageData(this.id);
    this.getValue();
  },
  methods: {
    // 写入数据
    writeData(row) {
      for (let key in row) {
        for (let i = 0; i < this.drawingList.length; i++) {
          if (this.drawingList[i].vModel == key) {
            this.drawingList[i].defaultValue = row[key];
          }
        }
      }
    },
    // 对话框点击事件
    activeFormItem(element) {
      this.activeData = element;
      this.activeId = element.formId;
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getValue();
    },
    // 表单重置
    reset() {
      this.addForm = {};
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 新建按钮
    newPage() {
      this.addForm._id = undefined;
      for (let i = 0; i < this.drawingList.length; i++) {
        let drawingListType = this.drawingList[i].defaultValue;
        if (drawingListType instanceof Array) {
          this.drawingList[i].defaultValue = [];
        } else if (typeof drawingListType === "number") {
          this.drawingList[i].defaultValue = 0;
        } else {
          this.drawingList[i].defaultValue = "";
        }
      }
      this.drawingList = JSON.parse(JSON.stringify(this.drawingList));
      this.open = true;
      this.title = "新建";
    },
    // 提交申请
    submitApplication(row) {
      let data = {};
      data.map = row;
      data.table = this.id;
      data.id = row._id;
      console.log(data);
      submitApply(data).then(res => {
        if (res.code == 200) {
          this.getValue();
          this.msgSuccess("提交成功");
        }
      });
    },
    // 修改按钮
    handleUpdate(row) {
      var temp = [];
      temp = JSON.parse(JSON.stringify(this.drawingList));
      for (let key in row) {
        for (let i = 0; i < this.drawingList.length; i++) {
          if (this.drawingList[i].vModel == key) {
            temp[i].defaultValue = row[key];
          }
        }
      }
      this.drawingList = temp;
      this.addForm._id = row._id;
      console.log(row);
      this.open = true;
      this.title = "修改";
    },
    /** 表单数据 */
    _handleView(row) {
      this.clearAttributes = 1;
      this.openForm = true;
      this.title = "表单数据";
      this.writeData(row);
    },
    /** 审批历史 */
    handleViewHistoryList(row) {
      this.queryParams.processInstanceId = row.instance_id;
      this.showHistoryTable = true;
      this.getHistoryList();
    },
    getHistoryList: function() {
      this.loadingHistoryTable = true;
      return request({
        url: "/activiti/process/listHistory",
        method: "post",
        data: this.queryParams
      })
        .then(response => {
          this.historyList = response.rows;
          this.historyList.forEach(row => {
            row.startTime = format(row.startTime, "yyyy-MM-dd HH:mm:ss");
            row.endTime = format(row.endTime, "yyyy-MM-dd HH:mm:ss");
            row.durationInMillis = formatTotalDateSub(
              row.durationInMillis / 1000
            );
          });
          this.total = response.total;
          this.loadingHistoryTable = false;
        })
        .then(() => {});
    },
    /** 进度查看 */
    handleViewProcessImg(row) {
      const baseURL = process.env.VUE_APP_BASE_API;
      this.src =
        baseURL +
        "/activiti/process/read-resource?pProcessInstanceId=" +
        row.instance_id +
        "&_=" +
        new Date().getTime();
      console.log("src=" + this.src);
      this.srcList = [];
      this.srcList.push(this.src);
      this.scheduleOpen = true;
    },
    /** 删除按钮操作 */
    handleDelete() {
      let data = {};
      data.id = this.ids;
      data.table = this.id;
      this.$confirm(
        '是否确认删除页面自定义编号为"' + this.ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          console.log(data);
          return delPageValue(data);
        })
        .then(() => {
          this.getValue();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openForm = false;
    },
    // 提交按钮
    submitForm() {
      for (let i = 0; i < this.drawingList.length; i++) {
        let key = this.drawingList[i].vModel;
        let value = this.drawingList[i].defaultValue;
        this.addForm[key] = value;
      }
      let data = {};
      data.map = this.addForm;
      data.table = this.id;
      if (this.addForm._id != undefined) {
        data.id = this.addForm._id;
        editPageValue(data).then(res => {
          if (res.code == 200) {
            this.msgSuccess("修改成功");
            this.cancel();
            this.getValue();
          }
        });
      } else {
        addPageValue(data).then(res => {
          if (res.code == 200) {
            this.msgSuccess("新建成功");
            this.cancel();
            this.getValue();
          }
        });
      }
    },
    getPageData(id) {
      getPage(id).then(response => {
        if (response.code == 200) {
          console.log(response);
          this.form = response.data;
          let webData = this.form.webPageCode;
          if (webData != undefined) {
            this.webData = JSON.parse("[" + webData + "]");
            this.drawingList = this.webData;
          }
          let size = 0;
          this.tableTitleData = [];
          let arr = [];
          for (let i = 0; i < this.form.fieldList.length; i++) {
            let arg = {};
            if (this.form.fieldList[i].isShow == 1) {
              let a = this.form.fieldList[i];
              arg.name = a.name;
              arg.code = a.code;
              arg.dict = a.dict;
              arg.promptContent = this.form.fieldList[i].promptContent;
              arr.push(arg);
            } else {
              size++;
            }
          }
          this.tableTitleData = arr;
          // 用size的长度来判断表格是否有数据，从而决定显示或隐藏
          if (size == this.form.fieldList.length) {
            this.selectionShow = false;
            this.reviseShow = false;
          } else {
            this.selectionShow = true;
            this.reviseShow = true;
          }
        }
      });
    },
    getValue() {
      this.loading = true;
      this.queryParams.table = this.id;
      this.queryParams.map = this.alterForm;
      getAllPageValue(this.queryParams).then(res => {
        if (res.code == 200) {
          this.tableData = res.rows;
          this.total = res.total;
          this.loading = false;
          this.setTableData();
        }
      });
    },
    // 字典转换
    setTableData() {
      for (let n = 0; n < this.tableTitleData.length; n++) {
        this.getDicts(this.tableTitleData[n].dict).then(res => {
          for (let i = 0; i < this.tableData.length; i++) {
            for (const key in this.tableData[i]) {
              if (key == this.tableTitleData[n].code) {
                for (let d = 0; d < res.data.length; d++) {
                  if (this.tableData[i][key] == res.data[d].dictValue) {
                    this.tableData[i][key] = res.data[d].dictLabel;
                  }
                }
              }
            }
          }
        });
      }
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item._id);
      this.multiple = !selection.length;
    }
  }
};
</script>

<style scoped>
.revise-item {
  margin-top: 10px;
  padding: 0px 5px;
}
.revise-item el-input {
  width: 70px;
}
.table {
  margin: 5px 25px 0px;
}
.el-row {
  margin-top: 20px;
  padding: 5px 25px;
}
.box {
  margin: 40px;
  width: 400px;
}
</style>
